package cn.com.algery.temp.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.engine.FormService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.pvm.process.ProcessDefinitionImpl;
import org.activiti.engine.impl.pvm.process.TransitionImpl;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;

import cn.com.algery.temp.domain.Server;
  
  
/** 
 * Process operation core class
 * This core class mainly deals with: dismissing processes, retrieving processes, 
 * emptying the flow of specified active nodes, submitting process/process flow, 
 * suspending processes (privileged people approve directly, etc.), suspending, 
 * and other core operations
 *  
 *  
 */  
public class  activitiUtil{  
	
	private static ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
	private static RepositoryService repositoryService = processEngine.getRepositoryService();  
  
	private static RuntimeService runtimeService = processEngine.getRuntimeService();


	private static TaskService taskService = processEngine.getTaskService();


	private static FormService formService = processEngine.getFormService();


	private static HistoryService historyService = processEngine.getHistoryService();
	
	private static IdentityService identityService = processEngine.getIdentityService();


	/** 
     * Reject process
     *  
     * @param taskId 
     *            Current task ID 
     * @param activityId 
     *            Reject Node ID 
     * @param variables 
     *            Process storage parameters
     * @throws Exception 
     */  
    public static void backProcess(String taskId, String activityId,  
            Map<String, Object> variables) throws Exception {  
        if (StringUtils.isEmpty(activityId)) {  
            throw new Exception("Rejected target node ID is empty！");  
        }  
  
        // Find all parallel task nodes while rejecting
        List<Task> taskList = findTaskListByKey(findProcessInstanceByTaskId(  
                taskId).getId(), findTaskById(taskId).getTaskDefinitionKey());  
        for (Task task : taskList) {  
            commitProcess(task.getId(), variables, activityId);  
        }  
    }


	/** 
     * Retrieve process
     *  
     * @param taskId 
     *            Current task ID 
     * @param activityId 
     *            Reject Node ID 
     * @throws Exception 
     */  
    public static void callBackProcess(String taskId, String activityId)  
            throws Exception {  
        if (StringUtils.isEmpty(activityId)) {  
            throw new Exception("Target node ID is empty！");  
        }  
  
        // Find all parallel task nodes while retrieving
        List<Task> taskList = findTaskListByKey(findProcessInstanceByTaskId(  
                taskId).getId(), findTaskById(taskId).getTaskDefinitionKey());  
        for (Task task : taskList) {  
            commitProcess(task.getId(), null, activityId);  
        }  
    }


	/** 
     * Clear the flow of a specified activity node
     *  
     * @param activityImpl 
     *            Active node
     * @return Node flow collection
     */  
    private static List<PvmTransition> clearTransition(ActivityImpl activityImpl) {  
        // Store all current temporary variables of the current node
        List<PvmTransition> oriPvmTransitionList = new ArrayList<PvmTransition>();  
        // Get the current flow of the current node, store it in a temporary variable, and empty
        List<PvmTransition> pvmTransitionList = activityImpl  
                .getOutgoingTransitions();  
        for (PvmTransition pvmTransition : pvmTransitionList) {  
            oriPvmTransitionList.add(pvmTransition);  
        }  
        pvmTransitionList.clear();  
  
        return oriPvmTransitionList;  
    }


	/** 
	 * Submission process/process flow
     * @param taskId 
     *            Current task ID
     * @param variables 
     *            Process variables
     * @param activityId 
     *            Process goes to execute task node ID 
     *            This parameter is empty, the default is submit operation
     * @throws Exception 
     */  
    private static void commitProcess(String taskId, Map<String, Object> variables,  
            String activityId) throws Exception {  
        if (variables == null) {  
            variables = new HashMap<String, Object>();  
        }  
        // Jump node is empty, default submit operation
        if (StringUtils.isEmpty(activityId)) {  
            taskService.complete(taskId, variables);  
        } else {// Process steering operation
            turnTransition(taskId, activityId, variables);  
        }  
    }


	/** 
     * Suspension procedure (privileged person approves directly, etc.)
     *  
     * @param taskId 
     */  
    public static void endProcess(String taskId) throws Exception {  
        ActivityImpl endActivity = findActivitiImpl(taskId, "end");  
        commitProcess(taskId, null, endActivity.getId());  
    }


	/** 
     * According to the inflow task set, query the latest inflow task node
     *  
     * @param processInstance 
     *            
     * @param tempList 
     *            
     * @return 
     */  
    private static ActivityImpl filterNewestActivity(ProcessInstance processInstance,  
            List<ActivityImpl> tempList) {  
        while (tempList.size() > 0) {  
            ActivityImpl activity_1 = tempList.get(0);  
            HistoricActivityInstance activityInstance_1 = findHistoricUserTask(  
                    processInstance, activity_1.getId());  
            if (activityInstance_1 == null) {  
                tempList.remove(activity_1);  
                continue;  
            }  
  
            if (tempList.size() > 1) {  
                ActivityImpl activity_2 = tempList.get(1);  
                HistoricActivityInstance activityInstance_2 = findHistoricUserTask(  
                        processInstance, activity_2.getId());  
                if (activityInstance_2 == null) {  
                    tempList.remove(activity_2);  
                    continue;  
                }  
  
                if (activityInstance_1.getEndTime().before(  
                        activityInstance_2.getEndTime())) {  
                    tempList.remove(activity_1);  
                } else {  
                    tempList.remove(activity_2);  
                }  
            } else {  
                break;  
            }  
        }  
        if (tempList.size() > 0) {  
            return tempList.get(0);  
        }  
        return null;  
    }
    
    
    /** 
	 * Submission process/process flow
     * @param processKey 
     *            
     * @param variables 
     *             
     */  
    public static void startProcess(String processKey, String bussinessKey, Map<String, Object> variables) {
        if (variables == null) {  
            variables = new HashMap<String, Object>();  
        }  
    	runtimeService.startProcessInstanceByKey(processKey,bussinessKey,variables);
    }

	/** 
     * Get active node based on task ID and node ID
     *  
     * @param taskId 
     *             
     * @param activityId 
     *             
     *            If null or "", the current active node is queried by default
     *            If "end", the query end node
     *  
     * @return 
     * @throws Exception 
     */  
    private static ActivityImpl findActivitiImpl(String taskId, String activityId)  
            throws Exception {  
        ProcessDefinitionEntity processDefinition = findProcessDefinitionEntityByTaskId(taskId);  
  
        if (StringUtils.isEmpty(activityId)) {  
            activityId = findTaskById(taskId).getTaskDefinitionKey();  
        }  
  
        if (activityId.toUpperCase().equals("END")) {  
            for (ActivityImpl activityImpl : processDefinition.getActivities()) {  
                List<PvmTransition> pvmTransitionList = activityImpl  
                        .getOutgoingTransitions();  
                if (pvmTransitionList.isEmpty()) {  
                    return activityImpl;  
                }  
            }  
        }  
  
        ActivityImpl activityImpl = ((ProcessDefinitionImpl) processDefinition)  
                .findActivity(activityId); 
        return activityImpl;  
    }


	/** 
     * Query the task node that can be rejected based on the current task ID
     *  
     * @param taskId 
     *            
     */  
    public static List<ActivityImpl> findBackAvtivity(String taskId) throws Exception {  
        List<ActivityImpl> rtnList =  iteratorBackActivity(taskId, findActivitiImpl(taskId,  
                    null), new ArrayList<ActivityImpl>(),  
                    new ArrayList<ActivityImpl>());  
        return reverList(rtnList);  
    }

	/** 
     * Query the latest record of the specified task node
     *  
     * @param processInstance 
     *            
     * @param activityId 
     * @return 
     */  
    private static HistoricActivityInstance findHistoricUserTask(  
            ProcessInstance processInstance, String activityId) {  
        HistoricActivityInstance rtnVal = null;  
        List<HistoricActivityInstance> historicActivityInstances = historyService  
                .createHistoricActivityInstanceQuery().activityType("userTask")  
                .processInstanceId(processInstance.getId()).activityId(  
                        activityId).finished()  
                .orderByHistoricActivityInstanceEndTime().desc().list();  
        if (historicActivityInstances.size() > 0) {  
            rtnVal = historicActivityInstances.get(0);  
        }  
  
        return rtnVal;  
    }  
  
	/** 
     * According to the current node, whether the output flow of the query is a parallel end point,
     *  and if it is a parallel end point, the corresponding parallel start point ID is assembled.
     *  
     * @param activityImpl 
     *             
     * @return 
     */  
    private static String findParallelGatewayId(ActivityImpl activityImpl) {  
        List<PvmTransition> incomingTransitions = activityImpl  
                .getOutgoingTransitions();  
        for (PvmTransition pvmTransition : incomingTransitions) {  
            TransitionImpl transitionImpl = (TransitionImpl) pvmTransition;  
            activityImpl = transitionImpl.getDestination();  
            String type = (String) activityImpl.getProperty("type");  
            if ("parallelGateway".equals(type)) {
                String gatewayId = activityImpl.getId();  
                String gatewayType = gatewayId.substring(gatewayId  
                        .lastIndexOf("_") + 1);  
                if ("END".equals(gatewayType.toUpperCase())) {  
                    return gatewayId.substring(0, gatewayId.lastIndexOf("_"))  
                            + "_start";  
                }  
            }  
        }  
        return null;  
    }  
  
	/** 
     * Get process definition based on task ID
     *  
     * @param taskId 
     *            
     * @return 
     * @throws Exception 
     */  
    public static ProcessDefinitionEntity findProcessDefinitionEntityByTaskId(  
            String taskId) throws Exception {  
        ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService)  
                .getDeployedProcessDefinition(findTaskById(taskId)  
                        .getProcessDefinitionId());  
  
        if (processDefinition == null) {  
            throw new Exception("Process definition not found!");  
        }  
  
        return processDefinition;  
    }  
  
	/** 
     * Get the corresponding process instance based on the task ID
     *  
     * @param taskId 
     *             
     * @return 
     * @throws Exception 
     */  
    public static ProcessInstance findProcessInstanceByTaskId(String taskId)  
            throws Exception {  
        // 找到流程实例  
        ProcessInstance processInstance = runtimeService  
                .createProcessInstanceQuery().processInstanceId(  
                        findTaskById(taskId).getProcessInstanceId())  
                .singleResult();  
        if (processInstance == null) {   
            throw new Exception("Process instance not found!");  
        }  
        return processInstance;  
    }  
  
    /** 
     * Get task instances based on task ID
     *  
     * @param taskId 
     *            
     * @return 
     * @throws Exception 
     */  
    private static TaskEntity findTaskById(String taskId) throws Exception {  
        TaskEntity task = (TaskEntity) taskService.createTaskQuery().taskId(  
                taskId).singleResult();  
        if (task == null) {  
            throw new Exception("Task instance not found!");  
        }  
        return task;  
    }  
  
  
    /** 
     * Query all the peer task sets according to process instance ID and task key value
     *  
     * @param processInstanceId 
     * @param key 
     * @return 
     */  
    private static List<Task> findTaskListByKey(String processInstanceId, String key) {  
        return taskService.createTaskQuery().processInstanceId(  
                processInstanceId).taskDefinitionKey(key).list();  
    }  
  
  
    /** 
     * Iterative loop process tree structure, query the current node can be rejected task node
     *  
     * @param taskId 
     *            
     * @param currActivity 
     *            
     * @param rtnList 
     *            
     * @param tempList 
     *           Temporary storage node collection (storage peer userTask node during one iteration)  
     * @return  
     */  
    private static List<ActivityImpl> iteratorBackActivity(String taskId,  
            ActivityImpl currActivity, List<ActivityImpl> rtnList,  
            List<ActivityImpl> tempList) throws Exception {  
        ProcessInstance processInstance = findProcessInstanceByTaskId(taskId);  
  
        List<PvmTransition> incomingTransitions = currActivity  
                .getIncomingTransitions();  
        // Conditional branch node collection, userTask node traversal is complete, iterate through this collection,
        // query the userTask node corresponding to the conditional branch
        List<ActivityImpl> exclusiveGateways = new ArrayList<ActivityImpl>();  
        // Parallel node collection, userTask node traversal is complete,
        // iterates over this collection, query the userTask node corresponding to the parallel node
        List<ActivityImpl> parallelGateways = new ArrayList<ActivityImpl>();  
        // Traverse the current node all inflow paths
        for (PvmTransition pvmTransition : incomingTransitions) {  
            TransitionImpl transitionImpl = (TransitionImpl) pvmTransition;  
            ActivityImpl activityImpl = transitionImpl.getSource();  
            String type = (String) activityImpl.getProperty("type");  
            /** 
             * Parallel node configuration requirements:
             * Must appear in pairs, and require to configure the node ID as: XXX_start (start), XXX_end (end)
             */  
            if ("parallelGateway".equals(type)) {// Parallel route
                String gatewayId = activityImpl.getId();  
                String gatewayType = gatewayId.substring(gatewayId  
                        .lastIndexOf("_") + 1);  
                if ("START".equals(gatewayType.toUpperCase())) {// Parallel starting point, stop recursion  
                    return rtnList;  
                } else {// Parallel end point, temporarily store this node, this cycle ends, 
                	 	// iterate the set, query the corresponding userTask node
                    parallelGateways.add(activityImpl);  
                }  
            } else if ("startEvent".equals(type)) {// Start node, stop recursion
                return rtnList;  
            } else if ("userTask".equals(type)) {
                tempList.add(activityImpl);  
            } else if ("exclusiveGateway".equals(type)) {
            	// Branch route, temporarily store this node, this cycle ends, iterate the set, 
            	// query the corresponding userTask node  
                currActivity = transitionImpl.getSource();  
                exclusiveGateways.add(currActivity);  
            }  
        }  
  
        /** 
         * Iterate condition branch set, query the corresponding userTask node
         */  
        for (ActivityImpl activityImpl : exclusiveGateways) {  
            iteratorBackActivity(taskId, activityImpl, rtnList, tempList);  
        }  
  
        /** 
         * Iterate parallel collections and query the corresponding userTask node
         */  
        for (ActivityImpl activityImpl : parallelGateways) {  
            iteratorBackActivity(taskId, activityImpl, rtnList, tempList);  
        }  
  
        /** 
         * Filters the most recently occurring nodes based on the same set of userTasks
         */  
        currActivity = filterNewestActivity(processInstance, tempList);  
        if (currActivity != null) {  
            // Query whether the flow direction of the current node is a parallel end point and obtain the parallel start ID
            String id = findParallelGatewayId(currActivity);  
            if (StringUtils.isEmpty(id)) {// The parallel starting point ID is empty,
            							  // this node's flow direction is not a parallel end point, 
            							  //and it meets the rejection condition and stores this node.
                rtnList.add(currActivity);  
            } else {
                currActivity = findActivitiImpl(taskId, id);  
            }  
  
            tempList.clear();  
            iteratorBackActivity(taskId, currActivity, rtnList, tempList);  
        }  
        return rtnList;  
    }  
  
  
    /** 
     * Restore the flow of a specified active node
     *  
     * @param activityImpl 
     *            
     * @param oriPvmTransitionList 
     *            
     */  
    private static void restoreTransition(ActivityImpl activityImpl,  
            List<PvmTransition> oriPvmTransitionList) {  
        List<PvmTransition> pvmTransitionList = activityImpl  
                .getOutgoingTransitions();  
        pvmTransitionList.clear();  
        for (PvmTransition pvmTransition : oriPvmTransitionList) {  
            pvmTransitionList.add(pvmTransition);  
        }  
    }  
  
    /** 
     * Reverse sorting of list collections to facilitate dismissal of nodes in order
     *  
     * @param list 
     * @return 
     */  
    private static List<ActivityImpl> reverList(List<ActivityImpl> list) {  
        List<ActivityImpl> rtnList = new ArrayList<ActivityImpl>();  
        for (int i = list.size(); i > 0; i--) {  
            if (!rtnList.contains(list.get(i - 1)))  
                rtnList.add(list.get(i - 1));  
        }  
        return rtnList;  
    }  
  
    /** 
     *  Transfer process
     *  
     * @param taskId 
     *             
     * @param userCode 
     *             
     */  
    public static void transferAssignee(String taskId, String userCode) {  
        taskService.setAssignee(taskId, userCode);  
    }  
  
    /** 
     *  Process steering operation
     *  
     * @param taskId 
     *            
     * @param activityId 
     *             
     * @param variables 
     *            
     * @throws Exception 
     */  
    private static void turnTransition(String taskId, String activityId,  
            Map<String, Object> variables) throws Exception {  
        ActivityImpl currActivity = findActivitiImpl(taskId, null);  
        List<PvmTransition> oriPvmTransitionList = clearTransition(currActivity);
        TransitionImpl newTransition = currActivity.createOutgoingTransition();  
        ActivityImpl pointActivity = findActivitiImpl(taskId, activityId);  
        newTransition.setDestination(pointActivity);  
        taskService.complete(taskId, variables);  
        pointActivity.getIncomingTransitions().remove(newTransition);  
  
        restoreTransition(currActivity, oriPvmTransitionList);  
    }  
    
   /* public static InputStream getImageStream(String taskId) throws Exception{
    	ProcessDefinitionEntity pde = findProcessDefinitionEntityByTaskId(taskId);
    	InputStream imageStream = ProcessDiagramGenerator.generateDiagram(  
				pde, "png",  
		runtimeService.getActiveActivityIds(findProcessInstanceByTaskId(taskId).getId()));
    	return imageStream;
    }*/
    
    /**
     * findTask(String userId,String instanceKey,Integer page, Integer pageSize,String filterItem)
     * @return Map<String,Object)
     */
    public static List<Task> findTask(String userId,String instanceKey,Integer startNum, Integer pageSize,String filterItem){  
    	if(filterItem == null) {
    		filterItem = "%%";
    	} else {
    		filterItem = "%"+ filterItem +"%";
    	}
		TaskService taskService = processEngine.getTaskService();
	    List<Task> taskList=taskService 
	            .createTaskQuery()
	            .processDefinitionKey(instanceKey)
	            .taskAssignee(userId)
	            .processVariableValueLikeIgnoreCase("server_name", filterItem.toString())
	            .listPage(startNum, pageSize);
	    return taskList;
	}
    
    /**
     * getTasksCount(String userId,String instanceKey,String filterItem)
     * @return Integer
     */
    public static Integer getTasksCount(String userId,String instanceKey,String filterItem){
    	if(filterItem == null) {
    		filterItem = "%%";
    	} else {
    		filterItem = "%"+ filterItem +"%";
    	}
		TaskService taskService = processEngine.getTaskService();
	    Integer count = (int) taskService
	            .createTaskQuery()
	            .processDefinitionKey(instanceKey)
	            .taskAssignee(userId)
	            .processVariableValueLikeIgnoreCase("server_name", filterItem.toString())
	            .count();
	    return count;
	}
    
    public static FormService getFormService() {
		return formService;
	}  
  
    public static HistoryService getHistoryService() {
		return historyService;
	}  
  
  
    public static ProcessEngine getProcessEngine() {
		return processEngine;
	}  
  
    public static RepositoryService getRepositoryService() {
		return repositoryService;
	}  
  
    public static RuntimeService getRuntimeService() {
		return runtimeService;
	}  
  
    public static TaskService getTaskService() {
		return taskService;
	}
    
    public static IdentityService getIdentityService() {
		return identityService;
	}
}  